请记住,声明和表格都有更多内容,但我会简短地阅读。
我正试图了解用户是否已经进入商店。表格看起来像这样。
--Shop--
ShopID
--Visit--
ShopID
UserID
以下是我现在已经走了多远。
SELECT shop.ShopID, visit.UserID AS Visited FROM shop
LEFT OUTER JOIN visit ON shop.ShopID = visit.ShopID
WHERE UserID = 1
此代码的问题在于,对于非UserID 1的访问,它不会显示NULL。我已尝试将OR UserID IS NULL
添加到语句中,但它只留给我所有尚未存在的商店任何用户访问过。
我可以通过检查Visited
是否与UserID相同来过滤它,但如果数据库可以将其写为1和0则会更容易。所以要问具体:
如果在访问表中与ShopID连接的UserID 1,如何使Visited
输出0或1?
答案 0 :(得分:1)
您加入的问题是您将所有商店ID保留在列表中,因为您只需创建一个扩展所有shop
和visit
s的列表使用未访问过的shop
。如果我找到你想要的是shop
所访问的user = 1
。只需使用Visit
表即可轻松实现这一目标。
Select DISTINCT visit.shopID FROM visit
WHERE UserID = 1
答案 1 :(得分:1)
Dennis Klopfer's answer是简化和表现的方法。但也许你想要更像这样的东西,检查某个用户曾经访问过每个商店:
Classfile /home/efrisch/workspace/StackOverflow/bin/com/stackoverflow/Main.class
Last modified Aug 22, 2015; size 410 bytes
MD5 checksum 6ba30603e8f16cbebc681a84061d38c3
Compiled from "Main.java"
public class com.stackoverflow.Main
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Class #2 // com/stackoverflow/Main
#2 = Utf8 com/stackoverflow/Main
#3 = Class #4 // java/lang/Object
#4 = Utf8 java/lang/Object
#5 = Utf8 ID_1
#6 = Utf8 I
#7 = Utf8 ConstantValue
#8 = Integer 1
#9 = Utf8 ID_2
#10 = Integer 2
#11 = Utf8 <init>
#12 = Utf8 ()V
#13 = Utf8 Code
#14 = Methodref #3.#15 // java/lang/Object."<init>":()V
#15 = NameAndType #11:#12 // "<init>":()V
#16 = Utf8 LineNumberTable
#17 = Utf8 LocalVariableTable
#18 = Utf8 this
#19 = Utf8 Lcom/stackoverflow/Main;
#20 = Utf8 test
#21 = Utf8 ()I
#22 = Utf8 SourceFile
#23 = Utf8 Main.java
{
public static final int ID_1;
descriptor: I
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: int 1
public static final int ID_2;
descriptor: I
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: int 2
public com.stackoverflow.Main();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #14 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 4: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this Lcom/stackoverflow/Main;
public static int test();
descriptor: ()I
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=0, args_size=0
0: iconst_3
1: ireturn
LineNumberTable:
line 9: 0
LocalVariableTable:
Start Length Slot Name Signature
}
SourceFile: "Main.java"
如果是这样的话,我会尝试这样的事情:
shop | visited by user 1
#1 | false
#2 | true
当然,您还可以在查询中添加 SELECT s.ShopID, IF(ISNULL(v.UserID), FALSE, TRUE) AS visited
FROM shop S LEFT JOIN visit v ON s.ShopID = v.ShopID AND v.UserID = 1
子句,并按任意字段过滤商店列表。
答案 2 :(得分:0)
SELECT shop.ShopID, if(visit.UserID is null,0,1) AS Visited FROM shop
LEFT OUTER JOIN visit ON (shop.ShopID = visit.ShopID
AND visit.UserID = 1 )
答案 3 :(得分:0)
我正在努力实现这一目标,我想:
v
您需要将ON
条件中的条件放在WHERE
子句而不是SELECT
子句中。
但是,如果用户可以多次访问,那么您将获得多行。所以,我建议在select s.ShopId,
(select v.UserId
from visit v
where s.SHopId = v.ShopId and v.userId = 1
limit 1
) as UserId
from shop s;
中使用子查询来获取用户的任意行:
a