开发者

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

开发者 https://www.devze.com 2023-03-19 04:38 出处:网络
MySQL table1: +----+--------+---------+------+ id | itemid |type| name | +----+--------+---------+------+

MySQL

table1:

+----+--------+---------+------+
| id | itemid |   type  | name |
+----+--------+---------+------+
| 1  |   1    | product |  t   |开发者_StackOverflow
+----+--------+---------+------+
| 2  |   2    | product |  t   |
+----+--------+---------+------+
| 3  |   3    | service |  t   |
+----+--------+---------+------+

table2:

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

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.

Further Explanation:

So, I want to see whether or not the row in table1 that matches t is a product.

If it is not a product (i.e. service), just go ahead and display it.

If it is a product, I want to further check whether or not its itemid is included in 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':

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:

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. 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
0

精彩评论

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