如何使用join在mysql中编写子查询代码

时间:2014-06-20 06:29:00

标签: php mysql

我需要从子查询的两个表中获取数据....我尝试了一些查询但是... 结果不明 如何从具有相同id的两个表中获取数据 我试过这个......我需要从两个表中获取记录,用于lastlogin deatil和总登录数........................... .................................................. ..........

SELECT 
  `name` uname,
  pwd,
  mob,
  dor,
  mob1,
  fld_point,
  fld_count,
  logindetail 
  (SELECT 
    COUNT(*) 
  FROM
    tbl_lastlogin_log 
  WHERE fld_userName = 'all') AS total_visits from fruser
WHERE uname = 'fruser' 

4 个答案:

答案 0 :(得分:0)

我不知道你的表结构,但是我可以给你结构你需要用于连接的结构。你去吧,

如果你有两个表(table1,table2)并想从这两个表中获取一些字段。然后,

select table1.field1, table1.field2,table2.field1, table2.field2 from table1 inner join  table2 on table1.field1 = table2.field1 where table1.field1 = "value";

这将在那个条件(table1.field1 = table2.field1)上连接这两个表(table1,table2)。从结果集中,它将过滤where where condition(table1.field1 =“value”)。

想要了解有关SQL连接的更多信息,请使用此选项 - http://www.w3schools.com/sql/sql_join.asp

答案 1 :(得分:0)

从你的问题中不清楚你究竟想做什么。但你可以试试这个:

SELECT col1, col2, col3,
(select cc from another_table at where at.fld_userName = t.uname) as cc,
(select ccc from yet_another_table yat where yat.fld_userName = t.uname) as ccc
from table t
where uname = 'fruser';

答案 2 :(得分:0)

正如Saqueib所指出的,您在查询中错过了FROM。我准备了一个小提琴来证明这个原则:

http://sqlfiddle.com/#!2/99d67/3

user

+-------------------+
| UANME | PASSWORD  |
+-------------------+
| userA | secretA   |
| userB | secretB   |
+-------------------+

lastlogin

+----------+------------+
| USERNAME | DATE       |
+----------+------------+
| userA    | 2014-01-01 |
| userA    | 2014-01-02 |
| userA    | 2014-01-03 |
| userA    | 2014-01-04 |
| userB    | 2014-02-01 |
| userB    | 2014-02-10 |
+----------+------------+

查询:

SELECT uname, (
               SELECT COUNT(*) FROM lastlogin WHERE username = uname
              ) AS logincount
FROM user;

结果:

+-------+------------+
| UNAME | LOGINCOUNT |
+-------+------------+
| userA | 4          |
| userB | 2          |
+-------+------------+

答案 3 :(得分:0)

试试这个,你在查询中有语法错误,你的查询没问题,不需要JOIN

SELECT 
  `name` uname,
   pwd,
   mob,
   dor,
   mob1,
   fld_point,
   fld_count,
   logindetail, //Here you missed the comma
   (SELECT COUNT(*) 
      FROM tbl_lastlogin_log 
    WHERE fld_userName = 'all') AS total_visits 

FROM fruser
    WHERE uname = 'fruser'