MySQL如何选择字段等于另一表中的某些东西?
以两个示例表为例:
TableOne
+----+----------+-------------+------------+------------+--+
| id | uid | thingone | thingtwo | thingthree | |
+----+----------+-------------+------------+------------+--+
| 1 | 7 | 0 | 1 | 1 | |
| 2 | 8 | 1 | 1 | 0 | |
+----+----------+-------------+------------+------------+--+
因此,
TableTwo
+----+----------+-------------+------------+------------+--+
| id | oid | thingone | thingtwo | thingthree | |
+----+----------+-------------+------------+------------+--+
| 1 | 7 | Apple | Coconut | Grape | |
| 2 | 8 | Potato | Orange | Banana | |
+----+----------+-------------+------------+------------+--+
在此示例中,用户ID 7将获得椰子和葡萄,而不是Apple。 UserId 8会得到马铃薯和橙色,但不能获得香蕉。我想以最有效的方式执行此操作,我意识到我可以通过一些PHP处理进行两个单独的查询,但是如果可行的话,我想用单个查询进行操作。
我需要做的是(在一个查询中)从tableone中获取行,然后从tabletwo中从tabletwo中选择theoid = tableone的id的行,但仅在tableone中从tabletwo中获取相应的行,而不是0 。
有人可以帮忙吗?
Take two example tables:
TableOne
+----+----------+-------------+------------+------------+--+
| id | uid | thingone | thingtwo | thingthree | |
+----+----------+-------------+------------+------------+--+
| 1 | 7 | 0 | 1 | 1 | |
| 2 | 8 | 1 | 1 | 0 | |
+----+----------+-------------+------------+------------+--+
and
TableTwo
+----+----------+-------------+------------+------------+--+
| id | oid | thingone | thingtwo | thingthree | |
+----+----------+-------------+------------+------------+--+
| 1 | 7 | Apple | Coconut | Grape | |
| 2 | 8 | Potato | Orange | Banana | |
+----+----------+-------------+------------+------------+--+
So in this example userid 7 would get Coconut and Grape, but not Apple. Userid 8 would get Potato and Orange, but not banana. I am wanting to do this the most efficient way and I realize I could do two separate queries with some php processing, but I want to do it with a single query if feasible.
What I need to do is (in a single query) get the row from TableOne by id and then select the row from TableTwo where theoid = the id of TableOne but only get the corresponding row from TableTwo if it is 1 and not 0 in TableOne.
Can any one help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用使用并比较两个表1 x 1的列来实现它。要比较tableone的tablewo,您需要使用加入,在此查询中,我使用左JOIN。
检查 mysql if()function function 以获取更多详细信息。
You can achieve it by using
IF
and comparing the columns from both tables 1 by 1. To compare the tabletwo from tableone you need to use JOIN, in this query I use a LEFT JOIN.Check MySQL IF() Function for more details.
您需要制作关系表,然后使用加入查询
you need to make relational tables and then use join query
那又如何:
您可能需要将这三个行连接或将它们转换为三行,这取决于如何表示三件事。
What about this:
You might need to concatenate these three or convert them into three rows, depending how how the three things should be represented.