我在数据库中有2个表。
表1:用户 id,name,email,password,singleCourse,userType,
表2:userCourses id,fk_user_id,course_name
userType可以是1或2.
现在,如果userType = 1
继续从用户表中获取。
如果userType = 2
从userCourses表中获取包含多个记录的表。
需要查询逻辑方面的帮助。
除非有需要,否则查询不应从userCourses表中获取记录。
那么可以使用CASE吗?
以下是我尝试的内容:
$query = mysql_query("SELECT name.user,email.user,password.user,userType.user,
fk_user_id.course,course_name.course
FROM CASE userType.user WHEN 1 THEN FROM users.u
WHEN 2 THEN users.user INNER JOIN userCourses.course
ON (user.id = userCourses.fk_user_id)");
示例数据:
userCourses
1, John, john@test.com, 123456, 1, PHP
2, Nick, nick@test.com, 654321, 2, ''
userCourses:
1, 2, JAVASCRIPT
2, 2, C++
3, 2, Jquery
期望输出:
我只是想获取用户课程,但是如果usertype = 1
,使用所需的表,查询不应该转到另一个表来检查记录答案 0 :(得分:0)
我已发布如下的示例查询,根据您的要求进行修改
SELECT
(CASE field1
WHEN 'A' THEN 'value is A'
WHEN 'B' THEN 'value is B'
ELSE 'value is neither A or B'
END)
FROM your_table;
或
SELECT
(CASE
WHEN (field1 IS NULL) THEN 'value is NULL'
WHEN (field1 = 1) THEN 'value is 1'
ELSE 'value is neither NULL or 1'
END)
FROM your_table;
答案 1 :(得分:0)
虽然由于未知原因您没有提供所需的输出,但看起来您只需要这个
SELECT u.id, u.name, u.email, u.password, u.userType,
COALESCE(NULLIF(u.singleCourse,''), c.course_name) course
FROM users u LEFT JOIN userCourses c
ON u.id = c.fk_user_id
或
SELECT id, name, email, password, userType, singleCourse course
FROM users
WHERE usertype = 1
UNION ALL
SELECT u.id, name, email, password, userType, c.course_name
FROM users u JOIN userCourses c
ON u.id = c.fk_user_id
WHERE usertype = 2
示例输出:
+------+------+---------------+----------+----------+------------+ | id | name | email | password | userType | course | +------+------+---------------+----------+----------+------------+ | 2 | Nick | nick@test.com | 654321 | 2 | JAVASCRIPT | | 2 | Nick | nick@test.com | 654321 | 2 | C++ | | 2 | Nick | nick@test.com | 654321 | 2 | Jquery | | 1 | John | john@test.com | 123456 | 1 | PHP | +------+------+---------------+----------+----------+------------+
这是 SQLFiddle 演示
答案 2 :(得分:0)
更新的帖子/代码:
<?php
$query = mysqli_query("SELECT userType from user") or die("err:". mysqli_error());
$x = 1;
while($row = mysqli_fetch_array($query))
{
$userType[$x] = $row['userType']; // fetch all the userType in your table and put in an array
$x++;
}
for($x = 1; $x <= count($userType); $x++)
{
if($userType[$x]="1") // determines if the user is "1"
{
$query = mysqli_query("SELECT * FROM user") or die("Error" . mysqli_error());
}
else
{
$query = mysqli_query("SELECT u.*, c.* FROM user u LEFT OUTER JOIN userCourse c ON u.id = c.fk_user_id") or die(mysqli_error());
}
while(mysqli_fetch_array($query))
{
//code here whatever data you want to show
}
}
希望这会有所帮助。对早期代码的道歉。