【问题标题】:Select from two tables where left column IN content right column [duplicate]从左列IN内容右列的两个表中选择[重复]
【发布时间】:2018-02-25 02:14:33
【问题描述】:

我有两张桌子:

用户:

+-------+-------------+------+
| id    | name        | type |
+-------+-------------+------+
|   1   | Name 1      |  1   |
|   2   | Name 2      |  2   |
|   3   | Name 3      |  3   |
+-------+-------------+------+

消息:

+-------+-------------+-----------+----------+
| id    |  poster_id  |  message  | for_type |
+-------+-------------+-----------+----------+
|   1   |      3      |   mess1   |     1    |
|   2   |      2      |   mess2   |    2,3   |
|   3   |      1      |   mess3   |    3,1   |
+-------+-------------+-----------+----------+

在 for_type 中获取关于 $user_type 消息的查询是什么?

SELECT messages.*, users.name FROM messages LEFT JOIN users ON 
messages.poster_id = users.id WHERE messages.id > ' . $last_message_id . ' AND 
' . $user_type . ' IN (messages.for_type) 
ORDER BY news.id ASC

【问题讨论】:

标签: mysql


【解决方案1】:

如果我理解正确,您想选择一个特定的 for_type 并遇到该列未正确规范化的问题,具有多个值。如果您无法正确规范结构,则 where 子句中的 LIKE 命令将起作用,例如:

for_type LIKE "%1%"

将从消息中获取记录 1 和 3。

【讨论】:

  • 它只适用于小于 10 的数字 :)
  • 我正在考虑将 type_num 更改为 type_name 并使用 LIKE
  • 是的,使用 LIKE 可以在该列上提供大量潜在的解决方案。如果我有帮助,请给我们点赞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2016-02-27
相关资源
最近更新 更多