SQL JOIN not working the way i need - php

Hi guys im have trouble with a SQL join statement. i cant seem to get it to work the way i want
ex.
TABLE1 TABLE 2
ID NAME ID INFO
1 JOE 1 YES
2 MIKE 1 NO
3 JESS 1 MAYBE
4 ROB 2 NO
2 NO
$stid = oci_parse($conn, "
SELECT * FROM TABLE1 TBL1 RIGHT JOIN TABLE2 TBL2
ON (TBL1.ID = TBL2.ID0 WHERE TBL1.ID = '1'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
echo $row['NAME']."<br/ >";
echo $row['INFO']."<br/ >";
}
what i want to see is
RESULT
JOE
YES
NO
MAYBE
typically what i get (regardless of join type) is something like
JOE
YES
JOE
NO
JOE
MAYBE
any help would be great.

don't use rigth join, change it for left join
SELECT * FROM TABLE1 TBL1 LEFT JOIN TABLE2 TBL2
ON (TBL1.ID = TBL2.ID) WHERE TBL1.ID = '1'

First of all, you need to change the RIGHT JOIN to LEFT JOIN (or simple JOIN, check your requirements). Now for the main part of your problem: the JOIN works as expected, you need to use your favourite language to do something like that:
Pseudocode
var test_name = "";
var last_name = "";
while EXIST_MORE_RECORDS {
test_name = $row['NAME'];
if (test_name != last_name) {
last_name = test_name;
print last_name;
}
print $row['INFO']."<br/ >";
}

Look at the results of your query:
+----+------+----+-------+
| ID | NAME | ID | INFO |
+----+------+----+-------+
| 1 | JOE | 1 | MAYBE |
| 1 | JOE | 1 | NO |
| 1 | JOE | 1 | YES |
+----+------+----+-------+
Now look at your loop. You're outputting NAME and INFO for each row. You could alter your loop like #giorgos-altanis suggests.
You could also change your query to use UNION, and grab the NAME and INFO separately so that each is its own row.
select Name VALUE, 0 sortorder
from TABLE1
where ID = '1'
union
select Info VALUE, 1 sortorder
from TABLE2
where ID = '1'
order by sortorder
This would give you results like :
+-------+-----------+
| VALUE | sortorder |
+-------+-----------+
| JOE | 0 |
| MAYBE | 1 |
| NO | 1 |
| YES | 1 |
+-------+-----------+
Then you could use a simple loop. Hard to say whether this would be an appropriate solution to your actual code.
Note that the order of rows from Table2 cannot be guaranteed. If you want them to appear in order of YES, NO, MAYBE, you'll need an additional field in the table to define the sort order (or maybe a CASE statement).
UPDATE
If all you want is the count of the rows from Table2 (which is a completely different question), then you just need to join the tables and then group on the NAME:
select TBL1.ID, TBL1.NAME, COUNT(1) TBL2COUNT
from TABLE1 TBL1
join TABLE2 TBL2 on TBL1.ID = TBL2.ID
where TBL1.ID = '1'
group by tbl1.ID, TBL1.NAME

Related

Selecting one row value based on anothers row value

Hi, guys
Can't find answer in other topics, so asking here.
I have a Table in database
Table
------------------------------
id | name | last_name | created_by_id |
1 | Bilbo ..| Baggins.....| 0 .................... |
2 | Frodo . | Baggins.....| 1 ................... |
Is there any way i can get 1st row name value by using 2nd row created_by_id ?
I need to get sentence Frodo Baggins was created by Bilbo Baggins.
Can't find the right sql sentence
You need self join :
select t.*, t1.name, t1.last_name
from table t inner join
table t1
on t1.id = t.created_by_id
where t.id = 2;
you can just use a join
select *,<your string stuff here>
from <table> as a
inner join <table> as b
on a.id = b.created_by_id

MySQL SELECT with IF statement to set variable from another table

I want to show all the results from Table1 based on some select condition being true, and have a variable be set to 0 or 1 for each result from Table1 based on some satisfied condition with Table2.
SELECT * FROM Table1 WHERE Some_Condition=true
Foreach Table1.Name
SELECT IF(TID IS NULL, 0, 1) AS Variable FROM Table2
WHERE
Table2.Name=Table1.Name AND Table2.Val='p'
How can I make this all into one SQL call?
example call I would like to see is:
Table1:
+----+-------------------+
| ID | Name |
+----+-------------------+
| 1 | John |
+----+-------------------+
| 2 | Alan |
+----+-------------------+
Table2: So here Alan exists AND Val='p', not just existing
+-------+-----------+-----+
| TID | Name | Val |
+-------+-----------+-----+
| 1 | Alan | p |
+-------+-----------+-----+
SQL result I want from a SINGLE SELECT statement:
+------+----------+
| Name | Variable |
+------+----------+
| John | 0 |
+------+----------+
| Alan | 1 |
+------+----------+
A LEFT JOIN and a CASE statement may work for you. Please see query below.
SELECT A.Name AS item, (CASE WHEN B.Val='p' THEN 1 ELSE 0 END) AS Variable
FROM Table1 A LEFT JOIN Table2 B ON (A.Name=B.Name)
I think you just want a JOIN:
SELECT t2.Name, IF(Tt2.ID IS NULL, 0, 1) AS Variable
FROM Table2 t2 JOIN
Table1 t1
ON t2.Name = t1.Name
WHERE t2.Val = 'p' AND <some condition on t1> = true;
In MySQL, you can simplify the SELECT to:
SELECT t2.Name, (Tt2.ID IS NOT NULL) AS Variable
Note that I added the name to the SELECT, although it is not in your sample SQL.
You need LEFT JOIN Table2 to include all rows from Table1 even if row in Table2 not exists. And then in Variable column just check if Table2.TID is presented (i.e. not null).
SELECT Name, (Table2.TID IS NOT NULL) AS Variable
FROM Table1
LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'
Or it can be done with IF():
SELECT Name, IF(Table2.TID IS NULL, 0, 1) AS Variable
FROM Table1
LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'

MYSQL left join if then statement favorite table procedure

i have 2 tables
here is table 1 table name is
forexample
itemlist
+-----+----------+-----+
| uid | username | age |
+-----+----------+-----+
| 1 | doe | 17 |
| 2 | smith | 18 |
| 3 | john | 30 |
+-----+----------+-----+
and other one is
fav
+-----+------+---------+
| uid | user | itemuid |
+-----+------+---------+
| 1 | alex | 2 |
+-----+------+---------+
Here is my mysql query *NOT Working * any way to fix this problem when i run php file i got error in mysql syntax
SELECT c.uid, c.username, c.age,i.uid,i.user,i.itemuid
from itemlist c
left join fav i on c.uid = i.itemuid
if (i.user = 'alex') THEN
SET #fav = 1;
ELSE
SET #fav = 0;
END IF
this is sample php
while ($row = mysqli_fetch_array($res)){
if ($row['fav'] = '1'){
echo $row['username']." is exit in fav";
}else{
echo $row['username']." is not exit in fav";
}
}
i hope you understand my question right ?
To get a column named fav returned in the resultset, you would need to include an expression in the SELECT list, and give it an alias fav.
It's not at all clear why you would need a MySQL user-defined variable; if you don't know why you'd need one, then you probably don't need one.
Given that your PHP code is looking for a column named fav in the resultset, likely you want something like this:
SELECT c.uid
, c.username
, c.age
, i.uid AS i_uid
, i.user
, i.itemuid
, IF(i.user='alex',1,0) AS fav
FROM itemlist c
LEFT
JOIN fav i ON i.itemuid = c.uid
Note that the original query had two columns named uid; if you want to return both, and be able to reference both of those by column name, you need to have distinct names for each. In the query above, I've assigned an alias to the i.uid column so that both uid columns will be available by distinct column name.

Mysql - join 2 queries with limit

Im not very familiar with using 'join' in queries. I really tried solving this by my own, but it seems to be too hard.
I got 2 Tables:
Table 'users':
+-----------------+-----------------+
| member | online |
+-----------------+-----------------+
| mahran | 1 |
| peter | 1 |
| Jen | 1 |
| Steve | 0 |
+-----------------+-----------------+
Table 'tickets'
+-----------------+----------------+----------------+
| name | category | time |
+-----------------+----------------+----------------+
| mahran | silver | 1 |
| peter | blue | 1 |
| mahran | blue | 2 |
| peter | red | 3 |
| peter | green | 2 |
| Jen | silver | 1 |
+-----------------+----------------+----------------+
The chellange:
I need each member (users.member) who's online (users.online). The next thing is to get the category for each member (user.member = tickets.name) with the highest time (probably ORDER BY time DESC LIMIT 1).
So, for example:
Peter is online. Peters highest time is 3 at the position of category=red. So I want peter to show up in the result with his category 'red'. Mahran would show up with blue. Jen would get silver. And steve would be left out because he's not online.
I hope this was clear. In general I know how the queries would look like but theres no chance for me merging them together.
What needs to be merged:
SELECT member FROM users WHERE online = 1;
|
v for each member
SELECT category FROM tickets WHERE name=users.member ORDER BY time DESC.
So, any ideas how to solve this?
Here is a fiddle with a not working query: Click
You can do this easily with a correlated subquery:
select u.member,
(select t.category
from tickets t
where t.name = u.member
order by t.time desc
limit 1
) as MostRecentCategory
from users u
where u.online = 1;
This can make use of the following indexes: users(online, member) and ticket(member, time, category).
Here is the query you're looking for:
SELECT U.member
,T.category
FROM users U
INNER JOIN tickets T ON T.name = U.member
INNER JOIN (SELECT T2.name
,MAX(T2.time) AS [maxTime]
FROM tickets T2
GROUP BY T2.name) AS M ON M.name = T.name
AND M.maxTime = T.time
WHERE U.online = 1
The use of [name] to join the two tables is not a good practice, it's much better to use keys instead. But my query is just here to help you understanding the process of jointure.
Hope this will help you.
If i understand you correctly
SELECT DISTINCT users.member, tickets.category FROM tickets JOIN users ON users.member = tickets.name WHERE users.online = 1 ORDER BY tickets.time DESC
Can you make sql fiddle?
USE DISTINCT
stackoverflow.com/questions/11704012/mysql-distinct-join
try this
SELECT DISTINCT User.member,Ticket.category FROM users AS USER
INNER JOIN tickets AS Ticket ON (User.member = Ticket.name)
WHERE User.online = 1;
Sorry, but peter seems to be RED, It's time is 3. Don't you?
Depending on table definition, is not guaranteed to have one only result for each user.
For example, if peter has time 3 in two categories, you can get one different category depending of the SQL sorting method.
To be sure, tickets.Category and tickets.time must be in a unique key (both toghether, not a unike key for each field)
Assuming that, the Query could be this.
select t2.name, t2.category
from
tickets t2
INNER JOIN (Select
u.member, max(time)
from users u, tickets t
where
u.member = t.name
and u.online = 1
group by u.member
) as usermaxtime on t2.name = usermaxtime.member;

Need to update missing info in mySQL table column

I'm back again. Been searching and trying this for hours... Haven't found an answer or even the right question.
I want to fix a crashed table that I recreated from memory (and the members list in Works) using an query in phpMyAdmin. I need to populate each members total posts.
forum_messages
member_id | message |
--------------------
1 | Hello |
3 | One, Two, Three |
1 | Howdy! |
2 | Here we are again! |
2 | To answer your question... |
forum_members
member_id | posts |
--------------------
1 | 0 |
2 | 0 |
From forum_messages, forum_members should end up looking like this:
forum_members
member_id | posts |
--------------------
1 | 2 |
2 | 2 |
3 | 1 |
Thanks!
Using an INSERT SELECT query, you should be able to rebuild the data you had lost in the forum_members table.
This would return the number of messages per member_id:
SELECT member_id, COUNT(*) FROM forum_messages GROUP BY member_id;
Collating it with an INSERT query puts it into the table instead of displaying the data as it normally would in an SELECT query.
INSERT INTO forum_members (member_id, posts) SELECT member_id, COUNT(*) FROM forum_messages GROUP BY member_id;
try this :
UPDATE forum_members SET posts = (SELECT COUNT(*) FROM forum_messages where forum_messages.member_id = forum_members.member_id GROUP BY forum_messages.member_id)
I think you need just to count messages by members, isn't it?
If so, use this SQL:
TRUNCATE TABLE forum_members;
INSERT INTO forum_members(member_id, posts)
SELECT member_id, COUNT(1) FROM forum_messages GROUP BY member_id;
This should fix it.. Please note that the code is NOT TESTED. You should echo the outcome of the update query to check if it's correct before executing the update query
$get_memberid = "SELECT distinct(member_id) as member_id FROM forum_members;";
$Rget_memberid = mysql_query($get_memberid) or die(mysql_error());
while($row_get_memberid = mysql_fetch_array($Rget_memberid)) {
$arr_get_memberid[] = array( "member_id" => $row_get_memberid['member_id'] );
}
for ($c = 0; $c < count($arr_get_memberid); $c++){
$update_count = "UPDATE forum_members set posts = (SELECT count(member_id) from forum_messages where member_id = '".$arr_get_memberid[$c]['member_id']."') where member_id = '".$arr_get_memberid[$c]['member_id']."';";
$Rupdate_count = mysql_query($update_count) or die(mysql_error());
}

Categories