I have two tables in a database that looks like this
members table1
id | memberid | name | password
-------------------------------
Journal table2
id | memberid | title | desc
-----------------------------
i want to select all members from table one, joining with the result journal_count of each member in table 2. Am trying to count the number of times each memberid appears in table2
Am using mysql and php, can someone help me with this query
thanks
select m.memberid,m.name,count(j.memberid) as total
from members as m
left join journal as j
on m.memberid = j.memberid
group by m.memberid
P.S. If your table has a field named desc, beware that this is a reserved word and it would be better to rename it. Otherwise you'll always have to put it within backticks.
select m.memberid,m.name,count(j.memberid) as total
from members as m
left join journal as j
on m.memberid = j.memberid
where m.memberid = $memberid
group by m.memberid
select members.name, count(journal.memberid) as journal_count from members, journal where members.memberid = journal.memberid group by journal.memberid
Related
This query performs three JOIN operations with 3 tables. But is not ok i see..i'm trying to output all the rows in echo, but i have bad luck.
Mysql table columns:
tours
------
titlu_slider | desc_slider | poza_slider | poza_articol | pret
tours_review
----------
name | time_added | review_text
tours_overview
------------
descriere | titlu_box1 | desc_box1 | titlu_box2 | desc_box2 | titlu_box3 | desc_box3 | titlu_box4 | desc_box4
Php code:
<?php
$db = mysqli_connect("localhost", "root", "fidodido", "antonytravel");
$q = mysqli_query($db,"SELECT * FROM tours INNER JOIN tours_review INNER JOIN tours_overview WHERE id = ".$_GET['id']."");
while ($row = mysqli_fetch_assoc($q)) {
$titlu_slider=$row['titlu_slider'];
$desc_slider=$row['desc_slider'];
$poza_slider=$row['poza_slider'];
$poza_articol=$row['poza_articol'];
$pret=$row['pret'];
## Review table
$name_review=$row['name'];
$time_added=$row['time_added'];
$review_text=$row['review_text'];
## Overview table
$descriere=$row['descriere'];
$titlu_box1=$row['titlu_box1'];
$desc_box1=$row['desc_box1'];
$titlu_box2=$row['titlu_box2'];
$desc_box2=$row['desc_box2'];
$titlu_box3=$row['titlu_box3'];
$desc_box3=$row['desc_box3'];
$titlu_box4=$row['titlu_box4'];
$desc_box4=$row['desc_box4'];
echo '<section class="parallax_window_in" data-parallax="scroll" data-image-src="'.$poza_slider.'" data-natural-width="1400" data-natural-height="470">
<div id="sub_content_in">
<div id="animate_intro">
<h1>'.$titlu_slider.'</h1>
<p>"'.$desc_slider.'"</p>
</div>
</div>';
Some help needed..thanx.
You need to specify how how the tables relate to each other which might look something like the on conditions shown below (which are just guesses)
SELECT *
FROM tours t
INNER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever
You then face the issue of what type of join because if you have a tour with no reviews then you probably still want to list it. For that type of relationship you need an "outer join".
SELECT *
FROM tours t
LEFT OUTER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever
If every every tour has an "overview" then that can remain an "inner join"
EDIT: Please note that you need to prefix EVERY column reference with a table name or table alias (I have used table aliases to make the query shorter). If you don't do this your query may fail, e.g. if every table has a column id and you just ask for where id = 123 the query will not know which table to use and the query would error.
INNER join shows the records if there are matching record. Use OUTER join to show all records if it does not exists on other tables.
You are missing a few things in your query. Specifically related to the fields that link the tables. To do these joins the best practice is to name each table and then use that name to in an ON statement to JOIN the tables
So
SELECT * FROM tours
INNER JOIN tours_review
INNER JOIN tours_overview
WHERE id = ".$_GET['id'].""
Should be:
SELECT * FROM tours AS t
INNER JOIN tours_review AS r ON r.somefield = t.somefield
INNER JOIN tours_overview AS o ON o.somefield = t.somefield
WHERE id = ".$_GET['id'].""
MySQL can't join tables if it doesn't know what is connecting them.
I have multiple tables I am trying to grab data from in a single query. I seem to be close to a solution but can not seem to get the data result I am expecting.
Examples of my tables are as follows (fields have been truncated):
Table c
id
name
abbreviation
Table mr (relationship table tat ties tables c and m together by ID)
id
c.id
m.id
Table m
id
Table cnt
id
c.id
Table cmp
id
cnt.id
active
What I WANT is all fields from C, all fields from M where m.id = c.id, all active (active = 1) id's from CMP that match on cnt.id.
My most recent query (after dozens of iterations) is:
SELECT c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, c.active AS active
, c.last_modified AS last_modified
, c.modified_by AS modified_by
, mr.media_id
, mr.related_object_table
, mr.related_object_id
, m.orig_name AS img_name
, m.unique_name AS img_slug
, m.file_type AS confed_file_type
, m.file_size AS file_size
, COUNT('cmp.id') AS comps
FROM confederations AS c
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = c.id
AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
INNER JOIN countries AS cnt
ON cnt.confederations_id = c.id
INNER JOIN competitions AS cmp
ON cmp.countries_id = cnt.id
AND cmp.active = 1;
I am not proficient with Joins.
Basically, the result i am expecting is: For each Confederation (table C) I want that confederations name, abbreviation, active status (active), last modified date, modified by; from the Media Relationship table (table MR) I want the image id associated with that confederation so I can use that id to grab the image name and image slug for the confederations primary image from the Media table (M).
Now I also want the total number of Competitions (table CMP) for a given Confederation. Competitions are stored with a Country ID that is tied to the primary key ID of a country in the Countries Table (table CNT). Each Country in table CNT has a Confederations ID. So to get the total number of Competitions per Confederation I am 'trying' to get all Countries within their respective Confederation by CONFEDERATIONS_ID in table CNT, then foreach confederation I want select all the competitions from table CMP with matching COUNTRIES_ID from the group of country id's for that given confederation. (At this point i think i am confusing myself with how to get what i want)
Somehow I am getting the CORRECT NUMBER of competitions, but I am getting duplicate Confederations as results. For Example I am getting something similar to this (assume I have 3 different confederations with 2, 1, and 3 competitions respectively):
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 2;
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 1;
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 3
What am i doing wrong?
Through trial and error, I actually solved this on my own. I came back to post my answer and see Degan's answer, and though it is written differently than mine I think its very close to what I ended up with:
SELECT
cnf.id AS confed_id, cnf.name AS confed_name, cnf.abbreviation AS
confed_abbr, cnf.active AS confed_active, cnf.modified_by AS
confed_mod_by, cnf.last_modified AS confed_last_mod,
COUNT(cnt.id) AS total_countries,
COUNT(cmp.id) AS total_comps,
mr.media_id, mr.related_object_table, mr.related_object_id,
mr.primary_img,
m.orig_name AS img_name, m.unique_name AS img_slug, m.file_type AS file_type
FROM confederations AS cnf
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = cnf.id AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
LEFT JOIN countries AS cnt
ON cnt.confederations_id = cnf.id AND cnt.active = 1
LEFT JOIN competitions AS cmp
ON cmp.countries_id = cnt.id AND cmp.active = 1
GROUP BY cnf.id
So farthis seems to be giving me results i can use. I am not certain if my choice of Left Join for all my joins is in fact giving me everything i need (it SEEMS to be) and whether this will omit/add records once the tables get larger. If anyone can point out a problem in my query and my choice of using Left Join as opposed to a combination of LEFT and INNER JOINs as Degan did, that would be helpful.
When aggregating you need to group by.
Perhaps this is close to what you are looking for:
SELECT c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, m.orig_name AS img_name
, SUM('cmp.id') AS comps
FROM confederations AS c
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = c.id
AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
INNER JOIN countries AS cnt
ON cnt.confederations_id = c.id
INNER JOIN competitions AS cmp
ON cmp.countries_id = cnt.id
AND cmp.active = 1
GROUP BY c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, m.orig_name AS img_name
Hello I have two tables:
table1 - eod_stock
company_code | open | high | low | ltp | close | ycp | total_volume | total_value | datetime
table 2 - company
ID | code | name
here company code = code so to get all name and other info i used this code:
but first one gives me error and 2nd one returns only one row, but i need all 200 companies with their associated info.
select
company.code,
company.name,
eod_stock.open,
eod_stock.high,
max(eod_stock.datetime)
from
company
right join company on company.code= eod_stock.company_code;
and
select
eod_stock.company_code,
max(eod_stock.close),
eod_stock.total_volume,
eod_stock.total_trade,
eod_stock.high,
eod_stock.low,
eod_stock.ltp,
max(eod_stock.datetime),
company.name
from
eod_stock
inner join company on (company.code = eod_stock.company_code);
but first one gives me error and 2nd one returns only one row, but i need all 200 companies with their associated info.
The trick here is to start with a list of the max datetime for each company_code, which you can do with this basic query:
SELECT company_code, MAX(datetime) AS maxdatetime
FROM eod_stock
GROUP BY company_code
Join this to a query that gets company code, company name, and end-of-day values, and you should be all set:
SELECT
company.code,
company.name,
eod_stock.open,
eod_stock.high
FROM eod_stock
INNER JOIN company ON company.code = eod_stock.company_code
INNER JOIN (
SELECT company_code, MAX(datetime) AS maxdatetime
FROM eod_stock
GROUP BY company_code) maxdt
ON maxdt.company_code = eod_stock.company_code AND
maxdt.maxdatetime = eod_stock.datetime
Your first error i guess that your have to write :
Table2 right join Table1
instead of company right join company
the 2nd one to get all company your full join !!
select
eod_stock.company_code,
max(eod_stock.close),
eod_stock.total_volume,
eod_stock.total_trade,
eod_stock.high,
eod_stock.low,
eod_stock.ltp,
max(eod_stock.datetime),
company.name
from
eod_stock
inner join company on (company.code = eod_stock.company_code) group by eod_stock.company_code;
dagfr was correct all i needed to add group by in the query.
I have two tables of which one is updated daily. I would like to display "only" the latest record for each row.
This is the query I am using now that of course returns all the records.
SELECT *
FROM ss_pumps, secondary_systems WHERE ss_pumps.id=secondary_systems.segment_id
ORDER BY id ASC
Any help would be greatly appreciated!
You can find the latest record for every segment_id by ID using subquery. The result of the subquery is then join against the two tables: ss_pumps and secondary_systems.
SELECT a.*, c.*
FROM ss_pumps a
INNER JOIN
(
SELECT segment_id, MAX(datefield) max_val
FROM secondary_systems
GROUP BY segment_id
)b ON a.id = b.segment_id
INNER JOIN secondary_systems c
ON b.segment_id = c.segment_id AND
b.max_val = c.datefield
Actually, I'm not sure how your tables: ss_pumps and secondary_systems are related with each other.
I think you want it the other ways,
SELECT a.*, b.*
FROM secondary_systems a
INNER JOIN ss_pumps b
ON a.segment_ID = b.segment
INNER JOIN
(
SELECT segment, MAX(ID) max_val
FROM ss_pumps
GROUP BY segment
) c ON b.segment = c.segment AND
b.ID = c.max_val
Use this query:
SELECT * FROM ss_pumps, secondary_systems WHERE ss_pumps.id=secondary_systems.segment_id ORDER BY id DESC LIMIT 1
This is assuming that id is an auto increment column and will always be inserted in order.
Here's what I got:
SELECT *
FROM
ss_pumps ssp
LEFT JOIN ( SELECT * FROM secondary_systems ORDER BY id DESC ) ss ON ( ssp.id = ss.segment_id )
GROUP BY
ssp.id
ORDER BY
ssp.id ASC
CAVEAT: I'm assuming that the secondary_systems has its own id field that also autoincrements. That's the only way you can make sure you're getting "only" the latest record for each row.
Demo: http://sqlfiddle.com/#!2/f816b/2/0
In my demo ss_pumps held the parents while secondary_systems held the children. Each parent has 3 children. All but the last children are boys. The last child is always a girl. According to your problem, the resulting query should yield only girls.
| ID | PARENT | SEGMENT_ID | CHILD |
------------------------------------
| 1 | mother | 1 | betty |
| 2 | father | 2 | tina |
I have two table one table containing station id and station name, and another table containing id, name, startStationId, endStationId. I know second table's id by using that id i need to fetch all details of second table with station name for corresponding startStationId, endStationId.
ex: table1
---------------------------------
slNo staionId staionName
---------------------------------
1 0012 Bangalore ,
2 0014 Chennai ,
3 0015 Mumbai
---------------------------------
Table 2:
------------------------------------------
Id Name startStationId endStationId
-------------------------------------------
123 Dhinesh 0014 0015
-------------------------------------------
For example i know second table id(123).. so i want to fetch all results by using id, result would be.
Id =>123, Name => Dhinesh, StartStaion =>Chennai , Endstation=>Mumbai.
How can we write in one single query...?
Thanks in advance.
Try this.
SELECT t2.Id,t2.name,t1.StationName,t3.StationName
FROM table2 t2
INNER JOIN table1 t1 ON t2.startStationId = t1.stationId
INNER JOIN table1 t3 ON t2.endStationId = t3.stationId
SELECT t2.Id, t2.Name, tstart.stationName , tend.stationName
FROM table2 as t2
INNER JOIN table1 as tstart ON t2.startStationId = tstart.stationId
INNER JOIN table1 as tend ON t2.endStationId = tend.stationId
this should work