开发者

MySQL concatenate to column while selecting

I'm dealing with a bit of a legacy database here, and I'm having some trouble with writing a search query.

The two tables concerned are products and tours (multiple per product).

My general quer开发者_如何学Cy looks like this:

SELECT products.*, tours.* FROM products INNER JOIN tours 
ON products.id=tours.product_id
GROUP BY products.id

Now here's the part where I'm having trouble. The products table contains a column, countries, which is a pipe-seperated list of country id's, like so: 13|45|33|29|133|337. I need to return a list of products that have, for example, country 33.

For simplicity, I could do where products.countries LIKE '%33%', but this would return 133 and 337 as well. I'll need to use where products.countries LIKE '%|33|%', but this won't match them if they're first or last. Therefore, I need to append a pipe to either end of the column value when selecting, which leaves me with something like:

SELECT products.*, tours.*, CONCAT("|",products.countries,"|") AS country_list
FROM products INNER JOIN tours ON products.id=tours.product_id
GROUP BY products.id

But if I attempt to add WHERE country_list LIKE '|%33%|', I get an "undefined index: country_list" error..

What am I doing wrong here?


You can use:

WHERE CONCAT("|",products.countries,"|") LIKE '%|33|%'

note that the pipes are within the percent signs


Aliases are not availible in WHERE clauses. Just in HAVING clauses

"An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column" 1

So you can either do

HAVING country_list LIKE '|%33%|'

Or the satement without Aliases, that Scott posted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜