1

Im trying to get some stats; total links, users and views, from 3 different tables. What im trying:

SELECT SUM(p.views), COUNT(c.id), COUNT(u.id)
FROM studenkel_userprefs as p, studenkel_content as c, studenkel_users as u

If I do them individually in three different queries, they work fine, but togheter the results gets a couple thousand times higher than what i want. I guess they multiply eachother in some way, Tips?

Thanks

Edit: Thanks guys, really appreciate your help, sorted it out.

3
  • 2
    When you list the tables this way FROM studenkel_userprefs as p, studenkel_content as c, studenkel_users as u it will give you a Cartesian product for all the rows from the three tables, it is also called CROSS JOIN you should use INNER JOIN but you need to specify how the three tables relate to each other, please update your question and show how they are related. Commented Oct 22, 2013 at 15:17
  • That query will result in a cartesian join, you need to join your tables together. Commented Oct 22, 2013 at 15:17
  • use a proper JOIN syntax, and tell the DB HOW those tables relate to each other, e.g. in this exact case you need a where clause: ... WHERE studenkel_userprefs.foo = studenkel_content.bar AND etc.... Commented Oct 22, 2013 at 15:18

3 Answers 3

2

What you're doing in your from is called implicit inner joins without criteria.

Which means your final view have p.rows * c.rows * u.rows rows and that's why you have weird result.

If you have 3 questions, ask them separately, not all at once.

Alternatively, if you really want only one request, you could go with something ugly as :

SELECT
  SELECT SUM(views) FROM studenkel_userprefs as "sum_userprefs",
  SELECT COUNT(id) FROM studenkel_content as "cnt_content",
  SELECT COUNT(u.id) FROM studenkel_users as "cnt_users"
FROM DUAL;
Sign up to request clarification or add additional context in comments.

Comments

0

Are you allowed to "cheat"?

SELECT
    (
        SELECT 
            SUM(p.views)
        FROM 
            studenkel_userprefs as p
    ) as `views`,
    (
        SELECT
            COUNT(c.id)
        FROM
            studenkel_content as c
    ) as `content_count`,
    (
        SELECT
            COUNT(u.id)
        FROM
            studenkel_users as u
    ) as `user_count`

Comments

0

This is because you are making a Cartesian join of the tables, which multiplies the number of rows in one table times the number of rows in each other table. Without specifying a join in either JOIN ... ON format or by specifying the join criteria in WHERE clause, this is the only result you will get.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.