php 将字符串与 MySQL 中的字段值连接起来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19261760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:08:13  来源:igfitidea点击:

Concatenate string with field value in MySQL

phpmysqlsqlconcatenation

提问by Ben

I have the need to concatenate a string with a field value in a MySQL query in order to LEFT JOIN two tables.

我需要在 MySQL 查询中将一个字符串与一个字段值连接起来,以便 LEFT JOIN 两个表。

Table one has a column called "category_id" with numeric values, such as 61, 78, 94 and such.

表一有一个名为“category_id”的列,其中包含数字值,例如 61、78、94 等。

Table two has a column called "query" which refers to a request route mechanism, and it has values such as "product_id=68", "category_id=74", "manufacturer_id=99" and so on.

表二有一个名为“query”的列,它指的是一种请求路由机制,它有“product_id=68”、“category_id=74”、“manufacturer_id=99”等值。

So in my query I require to join the tables when ever a concatenated string derived from a set string and the value of the "category_id" column matches the query field.

因此,在我的查询中,当从集合字符串派生的连接字符串和“category_id”列的值与查询字段匹配时,我需要加入表。

My SQL statement is currently:

我的 SQL 语句目前是:

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = 'category_id=' + tableOne.category_id

I have tried using the || operator instead of the + operator, but still no luck. Is it possible to do this in MySQL, or have I jumped the gun here?

我试过使用 || 运算符而不是 + 运算符,但仍然没有运气。是否可以在 MySQL 中执行此操作,或者我是否在这里过火了?

回答by Will Hannah

Have you tried using the concat()function?

您是否尝试过使用concat()函数?

ON tableTwo.query = concat('category_id=',tableOne.category_id)

回答by chadzheng

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

回答by David Namenyi

Here is a great answer to that:

这是一个很好的答案:

SET sql_mode='PIPES_AS_CONCAT';

SET sql_mode='PIPES_AS_CONCAT';

Find more here: https://stackoverflow.com/a/24777235/4120319

在这里找到更多:https: //stackoverflow.com/a/24777235/4120319

Here's the full SQL:

这是完整的 SQL:

SET sql_mode='PIPES_AS_CONCAT';

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = 'category_id=' || tableOne.category_id;

回答by Chris

MySQL uses CONCAT()to concatenate strings

MySQL 使用CONCAT()来连接字符串

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)