简体   繁体   English

如何在此 MySQL 查询中包含 IF 语句?

[英]How do I include an IF statement in this MySQL query?

MySQL MySQL

table1:表格1:

+----+--------+---------+------+
| id | itemid |   type  | name |
+----+--------+---------+------+
| 1  |   1    | product |  t   |
+----+--------+---------+------+
| 2  |   2    | product |  t   |
+----+--------+---------+------+
| 3  |   3    | service |  t   |
+----+--------+---------+------+

table2:表2:

+--------+---------+
| itemid | display |
+--------+---------+
|   1    |    1    |
+--------+---------+

PHP PHP

$a = mysql_query("SELECT * FROM `table1` WHERE `name` LIKE '%t' ....");

I want to modify the query above and also test:我想修改上面的查询并测试:

If type = product then itemid should not be included in table2 where display = 1 .如果type = product那么itemid不应包含在display = 1table2中。

Further Explanation:进一步说明:

So, I want to see whether or not the row in table1 that matches t is a product.所以,我想看看table1中匹配t的行是否是产品。

If it is not a product (ie service), just go ahead and display it .如果不是产品(即服务),只需在前面显示go 即可。

If it is a product, I want to further check whether or not its itemid is included in table2如果它一个产品,我想进一步检查它的itemid是否包含在table2

If it is included , then don't display it.如果包含,则不要显示它。

If it is not included , then display it.如果不包含,则显示它。

Sorry, I don't know how else to explain it.对不起,我不知道还能怎么解释。 :/ :/

If I understand you correctly, you want to exclude rows whose type = 'product':如果我理解正确,您希望排除 type = 'product' 的行:

SELECT * FROM table1 t1, table2 t2
WHERE t1.itemid = t2.itemid 
AND t1.id = '1' 
AND t1.type <> 'product'

(If that's not what you want, IMHO some further explanation is necessary) (如果这不是您想要的,恕我直言,需要进一步解释)

UPDATE: to exclude all whose type = 'product' having a matching row in table2:更新:排除所有 type = 'product' 在 table2 中具有匹配行的人:

SELECT * FROM table1 t1
WHERE t1.id = '1' 
AND (t1.type <> 'product' OR NOT EXISTS (
 SELECT NULL from table2 t2 
 WHERE t1.itemid = t2.itemid )

I'm a little confused about what exactly you are looking for, but I think you can accomplish your goal by building a select statement for each case of your IF statement, then unioning the results.我对你到底在寻找什么有点困惑,但我认为你可以通过为你的 IF 语句的每个案例构建一个 select 语句来实现你的目标,然后合并结果。 This may not be exactly what you're looking for (like I said, I'm a little confused) but I bet your solution will at least look close to this:这可能不是您正在寻找的东西(就像我说的,我有点困惑)但我敢打赌您的解决方案至少看起来接近这个:

SELECT * 
FROM table1
WHERE id = 1
AND type <> 'product'
UNION
SELECT t1.*
FROM table1 t1, table2 t2
WHERE t1.itemid = t2.itemid
AND t1.id =1
AND type = product
and t2.display <> 1

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

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