简体   繁体   English

PHP:MY​​SQL查询中有多个AND条件?

[英]PHP: multiple AND conditions in MYSQL query?

I'm trying to figure out why i cannot run a multiple AND conditions in mysql query. 我试图弄清楚为什么我不能在mysql查询中运行多个AND条件。

basically this is my code: 基本上这是我的代码:

SELECT id, category_name, url, category_name_unedit FROM mytable WHERE category_name='Girls Clothes' AND category_name='Boys Clothes' GROUP BY category_name

the code above doesn't return anything but when I run the code individually like this: 上面的代码不返回任何内容,但是当我像这样单独运行代码时:

SELECT id, category_name, url, category_name_unedit FROM mytable WHERE category_name='Girls Clothes' GROUP BY category_name

or like this: 或像这样:

SELECT id, category_name, url, category_name_unedit FROM mytable WHERE category_name='Boys Clothes' GROUP BY category_name

then it works fine! 然后就可以了!

This is such a basic issue and unfortunately i cannot figure out how to resolve it. 这是一个基本的问题,不幸的是我无法弄清楚如何解决它。

could someone please advise on this issue? 有人可以建议这个问题吗?

It's because the logic of the query is off. 这是因为查询逻辑已关闭。 If you think about it, you can't have a category name where its name is Girls Clothes AND Boys Clothes. 如果您考虑一下,就不能有一个类别名称,其名称是“ Girls Clothes AND Boys Clothes”。 However, you can have a result where the name is Girls Clothes OR Boys Clothes. 但是,您可能会得到名称为Girls Clothes或Boys Clothes的结果。

The query should look like: 查询应如下所示:

SELECT id, 
category_name, 
url, 
category_name_unedit 
FROM mytable 
WHERE category_name='Girls Clothes' 
OR category_name='Boys Clothes' 
GROUP BY category_name

I'm guessing that you want urls that are in both categories. 我猜想您想要两个类别的网址。 If so: 如果是这样的话:

SELECT url
FROM mytable 
WHERE category_name IN ('Girls Clothes', 'Boys Clothes')
GROUP BY url
HAVING COUNT(*) = 2;

If you just want to check for either category, then use IN in your query (or OR ). 如果您只想检查任一类别,则在查询中使用IN (或OR )。

SELECT id, category_name, url, category_name_unedit FROM mytable WHERE category_name='Girls Clothes' AND category_name='Boys Clothes' GROUP BY category_name

Because it is not possible for one item to have 2 category_name s. 因为一个项目不可能有2个category_name

What you probably intend is to find it if it is EITHER "Girls Clothes" or "Boys Clothes". 您可能打算查找的是“ Girls Clothes”还是“ Boys Clothes”。 In that case, you would use OR instead of AND. 在这种情况下,您将使用OR而不是AND。

SELECT id, category_name, url, category_name_unedit FROM mytable WHERE category_name='Girls Clothes' OR category_name='Boys Clothes' GROUP BY category_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM