itemlist
+-----+----------+-----+
| uid | username | age |
+-----+----------+-----+
| 1 | doe | 17 |
| 2 | smith | 18 |
| 3 | john | 30 |
+-----+----------+-----+
和另一个是
最爱
+-----+------+---------+
| uid | user | itemuid |
+-----+------+---------+
| 1 | alex | 2 |
+-----+------+---------+
这是我的mysql查询* NOT Working *以任何方式修复此问题当我运行php文件时我在mysql语法中出错
SELECT c.uid, c.username, c.age,i.uid,i.user,i.itemuid
from itemlist c
left join fav i on c.uid = i.itemuid
if (i.user = 'alex') THEN
SET @fav = 1;
ELSE
SET @fav = 0;
END IF
这是示例php
while ($row = mysqli_fetch_array($res)){
if ($row['fav'] = '1'){
echo $row['username']." is exit in fav";
}else{
echo $row['username']." is not exit in fav";
}
}
我希望你能理解我的问题吗?
答案 0 :(得分:1)
要获取结果集中返回的名为fav
的列,您需要在SELECT列表中包含一个表达式,并为其指定别名fav
。
为什么你需要一个MySQL用户定义的变量,这一点都不清楚;如果你不知道为什么需要一个,那么你可能不需要一个。
鉴于您的PHP代码正在查找结果集中名为fav
的列,可能您需要这样的内容:
SELECT c.uid
, c.username
, c.age
, i.uid AS i_uid
, i.user
, i.itemuid
, IF(i.user='alex',1,0) AS fav
FROM itemlist c
LEFT
JOIN fav i ON i.itemuid = c.uid
请注意,原始查询有两列名为uid
;如果要返回两者,并且能够按列名引用这两者,则需要为每个名称指定不同的名称。在上面的查询中,我为i.uid
列分配了一个别名,以便两个uid
列可通过不同的列名称使用。