假设我有两个表,一个包含法术列表,另一个包含一个grimory,一个用户选择学习或已经学习的法术列表。
mysql> SHOW COLUMNS FROM Grimory;
+--------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| personage_id | int(11) | YES | MUL | NULL | |
| spell_id | int(11) | YES | MUL | NULL | |
| isLearned | tinyint(1) | NO | | NULL | |
| isSelected | tinyint(1) | NO | | NULL | |
+--------------+------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
mysql> SHOW COLUMNS FROM Spell;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| description | longtext | NO | | NULL | |
| chatDescription | longtext | NO | | NULL | |
| level | int(11) | NO | | NULL | |
| isActive | tinyint(1) | NO | | NULL | |
| category_id | int(11) | YES | MUL | NULL | |
| createdAt | datetime | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
问题。
我想通过category_id显示包含所有法术的列表,但是如果该法术是由当前用户(personage_id)学习或选择的话,我想显示的每一行。
你能帮我写一个正确的查询吗?
这是如何运作的: 使用php我生成:法术列表|复选框isSelected | checkBox isStudied
当我点击isSelected复选框时,将使用当前用户和法术添加grimory中的记录。
答案 0 :(得分:2)
<强>更新强>
SELECT a.*, IFNULL(b.isLearned,0) as isLearned,
IFNULL(b.isSelected,0) as isSelected
FROM Spell a
LEFT JOIN Grimory b(ON b.spell_id =a.id
AND b.personage_id =:current_user_id)
WHERE a.category_id = :current_category_id
答案 1 :(得分:0)
SELECT * FROM Spell
INNER JOIN Grimory
ON Spell.id = Grimory.spell_id
WHERE (Grimory.isLearned = 1 OR Grimory.isSelected = 1)
AND Spell.category_id = 'YOUR CAT ID IS HERE'