MYSQL left join if then statement favorite table procedure - php

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.

Related

Using 1st SQL select statement results for 2nd select statement

I'd like some help combining Multiple SQL queries into one...
I have a search box for orderid or sampleref. An order may have up to 99 sampleref in it so I want the customer to be able to pull up a list of all sampleref associated with their order number regardless of if they search by orderid or one of their sampleref. Essentially what I want to do is,
SELECT `orderid` as OrderNumber FROM `results` WHERE `sampleref` = 'TEST12345';
SELECT * FROM `results` WHERE `orderid` = OrderNumber GROUP BY `sampleref`;
For clarity I'm putting this into a PHP script for a Maria DB mysql server
Here is a sample database
+----+---------+-----------+
| id | orderid | sampleref |
+----+---------+-----------+
| 1 | 101388 | TEST12345 |
| 2 | 101388 | TEST54321 |
| 3 | 333444 | ABC123 |
| 4 | 333444 | ABC321 |
+----+---------+-----------+
Thanks
Henry
Following will give you what you are looking for.
select r2.orderid, r2.sampleref
from result r
join result r2 on r.orderid = r2.orderid
where r.sampleref = 'TEST12345' or r.orderid = <orderid>
You can use or with a correlated subquery:
SELECT r.*
FROM results r
WHERE r.orderid = $orderid OR
EXISTS (SELECT 1
FROM results r2
WHERE r2.orderid = r.orderid AND r2.sampleref = $sampleref
);
Note: This takes two parameters -- either the order id or the sample ref. The first condition returns everything with the same order, if that is given. The second returns everything with the same order as the given sample ref.

SQL need to improve run speed

I am trying to select data from mysql by a date field in the database. (Users can enter start date and end date)
For each selected row between user selected dates, I need to select from the same table to produce a result.
Example:
$query = "SELECT * FROM table WHERE date BETWEEN $begindate AND $enddate"; //Select by date
$result = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($result)){
vardump($row); //user needs to see all data between date selection
$query = "SELECT * FROM table WHERE field = $row['field']";
// and then do calculations with the data
}
This runs very slowly and I can see why. How can I improve the run speed?
Edit:
The original purpose was to generate a sales report between dates. Now the user wants the report to produce another result. This result could only be produced by searching against the same table, and the rows that I need is not within the date selection.
Edit 2:
I do need to output the entire table between date selection. Each row will need to find ALL other rows where field = field, within or out side of the date selection.
Edit 3: Solved the problem. All the answers are helpful, though I think the chosen answer was most related to my question. However, I believe using join when working with two tables is the right way to go. For my problem, I actually just solved it by duplicating the table and run my search against the duplicated table. The chosen answer did not work for me because the second query selection is not a part of the first query selection. Hope this would help anyone looking at this post. Again, thanks for all the help!
Well, so if you are really looking for such a conditions in same table, I suggest you should use IN selector like following:
$query = "SELECT * FROM table
WHERE field IN
(SELECT DISTINCT field FROM table
WHERE
date BETWEEN $begindate AND $enddate)";
So final code will look some like following:
$query = "SELECT * FROM table
WHERE field IN
(SELECT DISTINCT field FROM table
WHERE
date BETWEEN $begindate AND $enddate)";
$result = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($result)){
// do calculations with the $row
}
I guess your table names arent TABLE:
just user inner join
$query = "SELECT *
FROM table1
JOIN table2
ON table1.field = table2.field
WHERE date BETWEEN $begindate AND $enddate
ORDER BY table1.field;"
Stop writing pseudo-SQL
SELECT * FROM is technically pseudo-SQL (a sql command which the interpreter has to modify before the command can be executed. It is best to get in a habit of specifying columns in the SELECT statement.
Use SQL joins
Joins are what makes relational databases so useful, and powerful. Learn them. Love them.
Your set of SQL queries, combined into a single query:
SELECT
table1.id as Aid, table1.name as Aname, table1.field as Afield,
table2.id as Bid, table2.name as Bname, table2.field
FROM table table1
LEFT JOIN table table2
ON table1.field = table2.field
WHERE table1.date BETWEEN $begindate AND $enddate
ORDER BY table1.id, table2.id
Your resulting print of the data should result in something which access each set of data akin to:
$previous_table1_id = 0;
while($row = mysqli_fetch_array($result)){
if ($row['Aid'] != $previous_table1_id) {
echo 'Table1: ' . $row['Aid'] . ' - ' . $row['Aname'] . ' - '. $row['Afield'] . "\n";
$previous_table1_id = $row['Aid'];
}
echo 'Table2: ' . $row['Bid'] . ' - ' . $row['Bname'];
}
Dealing with aggregated data
Data-aggregation (multiple matches for table1/table2 on field), is a complex subject, but important to get to know. For now, I'll leave you with this:
What follows is a simplified example of one of what aggregated data is, and one of the myriad approaches to working with it.
Contents of Table
id | name | field
--------------------
1 | foos | whoag
2 | doh | whoag
3 | rah | whoag
4 | fun | wat
5 | ish | wat
Result of query I gave you
Aid | Aname | Afield | Bid | Bname
----------------------------------
1 | foos | whoag | 1 | foos
1 | foos | whoag | 2 | doh
1 | foos | whoag | 3 | rah
2 | doh | whoag | 1 | foos
2 | doh | whoag | 2 | doh
2 | doh | whoag | 3 | rah
3 | rah | whoag | 1 | foos
3 | rah | whoag | 2 | doh
3 | rah | whoag | 3 | rah
4 | fun | wat | 4 | fun
4 | fun | wat | 5 | ish
5 | ish | wat | 4 | fun
5 | ish | wat | 5 | ish
GROUP BY example of shrinking result set
SELECT table1.id as Aid, table1.name as Aname
group_concat(table2.name) as field
FROM table table1
LEFT JOIN table table2
ON table1.field = table2.field
WHERE table1.date BETWEEN $begindate AND $enddate
ORDER BY table1.id, table2.id
GROUP BY Aid
Aid | Aname | field
----------------------------------
1 | foos | foos,doh,rah
2 | doh | foos,doh,rah
3 | rah | foos,doh,rah
4 | fun | fun, ish
5 | ish | fun, ish

SQL JOIN not working the way i need

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

mysql query 3 tables php output name instead id

Need some help.
I have got 3 tables. klients, klientwithservice, service.
table klients
id | klientrnd
---------
1 | 11231231
2 | 22222222
table service
id | servicename
---------
1 | Repair laptop
2 | Repair pc
table klientwithservice
id | klientrnd | serviceid
-------------------------------
1 | 11231231 | 1
2 | 11231231 | 2
3 | 22222222 | 1
4 | 22222222 | 2
I need to output SERVICENAME instead ID.
My sql query is:
SELECT serviceid FROM klientwithservice WHERE '$pole8' = `klientrnd`
Where $pole8 = klientrnd exactly person on which page i placed.
for this you need to JOIN two table
use below query
SELECT s.servicename FROM klientwithservice as kws
JOIN service as s ON s.id = kws.serviceid
WHERE `klientrnd` = '$pole8'
Firstly your sql SELECT serviceid FROM klientwithservice WHERE '$pole8' = klientrnd is wrong.
It will return a syntax error stating the unknown column $pole8 (it's exact value) `is wrong
Second you should use join to achieve what you're after. Try this:
SELECT s.servicename FROM klientwithservice as k
JOIN service as s ON s.id = k.serviceid
WHERE k.klientrnd = '$pole8'

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