how to select from two table in sql - php

i am creating a voting application and i want to select from the database tables and display the result .1 want to get the candidate name form the first table which i call candidate.sql and then get the amout of votes from the second table called voter.
this is the candidate.sql table
id | candidate
1 |**mark**
2 |**david**
3 |**jeff**
voter.sql
voter_id | forr |user |candidate_id
1 |**mark** |tobe | 1
2 |**david** |sandra| 2
3 |**jeff** |john | 3
4 |**jeff** |steve | 3
5 |**david** |linda | 2
6 |**mark** |ken | 1
7 |**mark** |jacob | 1
My question is how do i join it so it can display like a list. e.g
mark 3
david 2
jeff 2
or is there a better way.

SELECT forr,count(*) FROM voter
GROUP BY forr
ORDER BY 2 DESC

SELECT c.candidate, count(*)
FROM candidate c
JOIN voter v ON v.forr = c.candidate
GROUP BY c.candidate
ORDER BY count(*) DESC, c.candidate ASC

Related

How to select specific course by selecting course id and concatenate users all selected course with in same row

I am joining users table with selected_course table and course table with selected_course, my requirement is I want to get those users with course_id=2 and in same row select using concatenation of all courses which is selected by user.
user table
id name
1 user_1
2 user_2
user_education_details
id user_id education_id selected_course
1 1 1 2
2 2 1 2
3 1 2 4
4 3 1 2
5 3 2 4
Actual Requirement:
user_id required_course user_all_courses course_name
1 2 2,4 a,b
2 2 2 a
3 2 2,4 a,b
Using codeigniter query format:
$this->db->select('users.*');
$this->db->from('users');
$this->db->join('selected_course sc','c.user_id=users.id');
$this->db->join('course c','c.id=sc.selected_course');
$this->db->where('sc.selected_course',$course_id=2);
$this->db->get()->result();
A HAVING clause is what you're looking for. To filter data based on a group use this clause.
SELECT
ued.user_id,
2 AS required_course, -- passed course id
GROUP_CONCAT(ued.selected_course) AS user_all_courses,
GROUP_CONCAT(c.name) course_name
FROM user_education_details ued
INNER JOIN courses c ON ued.selected_course = c.id
GROUP BY user_id
HAVING SUM(IF(selected_course = 2, 1,0)) > 0;
Output:
| user_id | required_course | user_all_courses | course_name |
| 1 | 2 | 4,2 | b,a |
| 2 | 2 | 2 | a |
| 3 | 2 | 2,4 | a,b |
You can also order user_all_courses and course_name by using a ORDER BY clause inside GROUP_CONCAT. Here is one example.
GROUP_CONCAT(ued.selected_course ORDER BY selected_course ASC) AS user_all_courses,
Now you can quickly convert this to your equivalent CodeIgniter query.
Check this working fiddle for the same.

How do I get distinct rows by a column?

I have a huge number of rows that I'd like to get say, last 5 records inserted in that database from 10 different users. If the same user inserted the last 3 rows into database, we must get one row, skip the others two and move to get a row per user, until it count up to 5.
A database like that:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
1 | 4 | baa
4 | 5 | baa0
5 | 6 | baa1
5 | 7 | baa2
6 | 8 | baa3
7 | 9 | baa4
Should return:
user_id | news_id | title
1 | 1 | foo-1
2 | 2 | foo-2
3 | 3 | foo-3
4 | 5 | baa0
5 | 6 | baa1
The current filter was done by PHP, like this:
$used = array();
while ($data = mysql_fetch_array($query)) {
$uid = $data['user_id'];
if(in_array($uid, $used))
continue;
array_push($used, $uid);
// do something with data
}
But I want to refactor it, and do the filter purely by mysql, if possible. I don't know much MySql and that's why I'm having problem to archive this...
Here's what I've tried
select DISTINCT(user_id), news_id, title from XXX
WHERE GROUP BY (news_id) DESC
LIMIT 0,5
How can I do that?
1 way you can do it is to generate a partitioned row number per user and then select 5 records where RowNumber = 1.
SELECT *
FROM
(
SELECT
d.user_id
,d.news_id
,d.title
,(#rn:= if(#uid = user_id, #rn + 1,
if(#uid:=user_id,1,1)
)
) as RowNumber
FROM
Data d
CROSS JOIN (SELECT #uid:=-1, #rn:=0) vars
ORDER BY
user_id
,news_id
) t
WHERE
t.RowNumber = 1
ORDER BY news_id
LIMIT 5;
http://rextester.com/JRIZI7402 - example to show it working
Note you can change the row order by simply changing the ORDER BY statement of the derived table so if you have a column that will signify the latest record e.g. an identity column or a datetime column you can use that, but user_id must be the first criteria to be partitioned correctly.
Do it from your query.
"SELECT * FROM table GROUP BY user_id ORDER BY news_id DESC LIMIT 5"
well, i think this will achieve what you are after.
select user_id, news_id, title from tableName
GROUP BY user_id
ORDER BY news_id DESC
LIMIT 0,5
Hope this helps!

PHP MySQLi how to get the most repeated value from a table

There's a little thing I'm stuck with. I've a table in my database like:
id | AuthorId | Book
---------------------
1 | 2 | book name
2 | 2 | book name
3 | 2 | book name
4 | 2 | book name
5 | 5 | book name
6 | 5 | book name
7 | 8 | book name
8 | 9 | book name
9 | 9 | book name
10 | 6 | book name
As you can see, Author ID "2" is repeated the highest times in this table ( 4 times ) while the author Author IDs appeared less then 4 times. How can I get the ID "2" from this table using php MySQLi, which is the most frequently occurring value in this data? I've no idea how can I do this.
Thank you very much.
Try the following query. You count rows grouped by AuthorID DESC , and limiting the result to the top value.
SELECT AuthorId, COUNT(AuthorId) as c from table
GROUP BY AuthorId
ORDER BY COUNT(AuthorId) DESC
LIMIT 1;
Try this
select AuthorId , count(AuthorId ) as max
from table_name
group by AuthorId order by max desc limit 1;
The order by max desc is for ordering the max value at the first row. The limit 1 is from getting only the first row

Symfony2 Finding Duplicate Rows and Summing Another Column

I am using Symfony2 and doctrine to grab all the duplicate rows and how many times they appear. That part I have down. Now, each of these rows has a qty field as well. What I am wanting to do is run my query and show how many times the duplicate row appears as well as sum the qty field for each of these rows:
My database table looks like this:
id | sku | qty
----------------------
1 A 1
2 B 1
3 A 3
4 A 5
5 A 1
6 A 1
7 B 2
8 A 1
9 A 1
Here is my initial query that grabs all duplicate rows:
SELECT o, count(o.id) as cnt
FROM WIC\APIBundle\Entity\FBAOrderHistory o
GROUP BY o.sku HAVING cnt > 1 order by cnt desc
It outputs this:
id | sku | cnt
----------------------
1 A 7
2 B 2
But what I want is this:
id | sku | cnt | qty
----------------------
1 A 7 13
2 B 2 3
Does anyone know how to do this. Thanks so much in advance for your help!
Use SUM()
SELECT o, count(o.id) as cnt ,sum(o.qty) as
FROM WIC\APIBundle\Entity\FBAOrderHistory o
GROUP BY o.sku HAVING cnt > 1 order by cnt desc
Using DQL
Mysql Demo

PHP Propel ORM MySQL - Left Join on Many to Many

I have two tables one called meeting and one called attendance, attendance is a many to many relational database in the following format:
Attendance:
user_id | meeting_id | invited
--------+------------+--------
1 | 5 | 1
2 | 5 | 0
3 | 4 | 0
3 | 5 | 1
3 | 6 | 0
Meetings are in the following format:
Meetings:
meeting_id | meeting_name | owner_id
-----------+--------------+----------
3 | Awesome | 2
4 | Boring | 2
5 | Cool | 5
9 | Sexy | 3
There can only be one meeting row per meeting, but unlimited attendance rows per meeting (limited to for every possible user for every meeting).
How in SQL and/or Propel do I create something that would list all meetings where the (provided) user_id is either the owner_id in meetings OR were the user_id and invited in the attendance database.
I am looking for a result (based on the above data) when searching for userid 3 of:
Result for userid3:
meeting_id | meeting_name | owner_id
-----------+--------------+----------
5 | Cool | 5 - Because userid 3 is attending meeting 5
9 | Sexy | 3 - Because userid 3 owns meeting 9
I currently have the following which doesn't work really, and produces multiple rows per meeting (because the meeting exists more than once in the attendance DB).
$criteria->addJoin(MeetingMeetingsPeer::ID, MeetingAttendancePeer::MEETING_ID, Criteria::LEFT_JOIN);
$criterion = $criteria->getNewCriterion(MeetingMeetingsPeer::OWNER_ID, Meeting::getUserId());
$criterion->addOr($criteria->getNewCriterion(MeetingAttendancePeer::USER_ID, Meeting::getUserId()));
$criteria->add($criterion);
return $criteria;
Which is something like the below in SQL:
SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME, meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH, meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT FROM `meeting_meetings` LEFT JOIN meeting_attendance ON (meeting_meetings.ID=meeting_attendance.MEETING_ID) WHERE (meeting_meetings.OWNER_ID=1 OR meeting_attendance.USER_ID=1)
Thanks for your time,
This should get you all meetings that are owned by user_id 1, as well as all meetings that are attended by user_id 1.
SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME,
meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH,
meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT
FROM `meeting_meetings`
WHERE `meeting_meetings`.`owner_id` = 1
UNION DISTINCT
SELECT meeting_meetings.ID, meeting_meetings.OWNER_ID, meeting_meetings.GROUP_ID, meeting_meetings.NAME,
meeting_meetings.COMPLETED, meeting_meetings.LOCATION, meeting_meetings.START, meeting_meetings.LENGTH,
meeting_meetings.CREATED_AT, meeting_meetings.UPDATED_AT
FROM `meeting_meetings`
JOIN `meeting_attendance` ON `meeting_meetings`.`meeting_id` = `meeting_attendance`.`meeting_id` AND `meeting_attendance`.`invited`
WHERE `meeting_attendance`.`user_id` = 1
It's a bit clunky. Personally, I would consider adding an owner flag to the meetings_attendance table.

Categories