优化:使SQL查询失控

时间:2017-07-17 08:29:07

标签: java mysql sql loops optimization

我有两个表与1到n的关系。 表爱好为表用户提供了一个名为" userid"

的外键
SELECT * FROM hobbies WHERE userid = 7

可以有多个结果。 表用户包含用户配置文件数据列表,表爱好包含用户爱好列表。我想打印多个用户的个人资料信息列表,其中包含每个用户的爱好。 (业余爱好连成一个字符串) 我目前有以下sql查询:(伪代码):

ResultSet result = executeQuery("SELECT * FROM users;");

for each returned row: executeQuery("SELECT * FROM hobbies WHERE userid =" + result.getInt("ref"));

如何从循环中获取SQL查询以优化大量用户的性能?

我正在尝试执行LEFT JOIN然后在java中而不是在SQL中执行WHERE ref = check 问题是我然后得到重复的用户,我只想在处理结果集时为每个用户打印一行 我也不确定JOIN是否真的是性能上的提升,因为我必须处理更多的行。

table users
+--------+------+---------+--------+
| userid | name | country | telno  |
+--------+------+---------+--------+
|      1 | John | USA     | 123456 |
|      2 | Max  | Germany | 345678 |
+--------+------+---------+--------+

+--------------+------------+
| userid       |hobby       |
+--------------+------------+
|            1 | football   |
|            1 | basketball |
|            2 | TV         |
|            2 | Music      |
|            2 | football   |
+--------------+------------+

example output:
John, USA, 123456, {football, basketball}
Max, Germany, 345678, {TV, Music, football}

4 个答案:

答案 0 :(得分:0)

您可以尝试:

SELECT h.userid, h.allyouneed FROM hobbies h, users u WHERE h.userid =u.userid

并在一个查询中获取信息

答案 1 :(得分:0)

"SELECT * FROM hobbies h join users u on h.userid = u.userid WHERE userid = ?"

preparedStatement.setInt(result.getInt("ref"));

然后,您可以将所有爱好保存到类似于下面“书籍”示例的列表中。

public static List<String> selectAll() throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        // THE LIST OF BOOKS YOU WILL RETURN
        List<String> books = new ArrayList<>();
        String sql = "SELECT BOOK FROM BOOKs";

        try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");){

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while(rs.next()){
                String book= rs.getString ("BOOK");
                // ADD BOOK TO THE LIST
                books.add(book);
            }
        }
        finally{
            ps.close();
            rs.close();
        }
        // RETURN LIST OF ALL BOOKS
        return books;
    }

答案 2 :(得分:0)

  List<TableItem> tableItems;
  protected override void OnCreate(Bundle bundle)
  {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Projlist);

        mToolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        SetSupportActionBar(mToolbar);
        SupportActionBar.Title = "قائمة طلبات المشاريع";

        Selling.WebServiceDB ws = new Selling.WebServiceDB();
        ws.MajorAListCompleted += Ws_MajorAListCompleted;
        ws.MajorAListAsync("المرحلة الجامعية");
    }

    private void Ws_MajorAListCompleted(object sender, Selling.MajorAListCompletedEventArgs e)
    {
        if (e.Result.ToString().Equals("0"))
        {

        }
        else
        {
            Spinner spinmajer = FindViewById<Spinner>(Resource.Id.spinmajer);
            List<String> datalist = new List<String>();
            foreach (var item in e.Result)
            {
                datalist.Add(item.MajorA);
            }
            var ArrayAdpter1 = new ArrayAdapter<String>(
            this, Android.Resource.Layout.SimpleSpinnerItem, datalist);
            spinmajer.Adapter = ArrayAdpter1;
            //spinmajer.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(spinmater3_ItemSelected);
            spinmajer.ItemSelected +=  spinmater3_ItemSelected ;
        }
    }

    private void spinmater3_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Spinner spinmajer = (Spinner)sender;
        string input2 = Convert.ToString(spinmajer.GetItemAtPosition(e.Position));

        Selling.WebServiceDB ws2 = new Selling.WebServiceDB();
        ws2.MaterDataLvlCompleted += Ws2_MaterDataLvlCompleted;
        ws2.MaterDataLvlAsync("المرحلة الجامعية", input2);
    }

    private void Ws2_MaterDataLvlCompleted(object sender, Selling.MaterDataLvlCompletedEventArgs e)
    {
        if (e.Result.ToString().Equals("0"))
        {

        }
        else
        {
            Spinner spinmater3 = FindViewById<Spinner>(Resource.Id.spinmater3);
            List<String> datalist = new List<String>();
            foreach (var item in e.Result)
            {
                datalist.Add(item.MaterNameA);
            }
            var ArrayAdpter1 = new ArrayAdapter<String>(
            this, Android.Resource.Layout.SimpleSpinnerItem, datalist);
            spinmater3.Adapter = ArrayAdpter1;
            //spinmater3.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(spinner1_ItemSelected);
            spinmater3.ItemSelected += spinner1_ItemSelected;
        }
    }

    private void spinner1_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Spinner spinmajer = (Spinner)sender;
        string sub = Convert.ToString(spinmajer.GetItemAtPosition(e.Position));

        Selling.WebServiceDB ws3 = new Selling.WebServiceDB();
        ws3.ProjectListCompleted += Ws3_ProjectListCompleted;
        ws3.ProjectListAsync(sub);
    }

    private void Ws3_ProjectListCompleted(object sender, Selling.ProjectListCompletedEventArgs e)
    {
        ListView listprojall = FindViewById<ListView>(Resource.Id.listprojall);
        string msg = "";

        if (e.Result.ToString().Equals("0"))
        {
            var callDialog = new AlertDialog.Builder(this);
            callDialog.SetTitle("Notify");
            callDialog.SetMessage(msg);
            callDialog.SetNeutralButton("The Customer Code is not correct", delegate { });
            callDialog.Show();
        }
        else
        {
            // full class
            tableItems = new List<TableItem>();
            foreach (var item in e.Result)
            {
                tableItems.Add(new TableItem(item.ProjName, item.Projansr, Convert.ToString(item.Projid)));
            }
            listprojall.Adapter = new HomeScreenAdapter(this, tableItems);
            //listprojall.ItemClick += OnlistItemClick;
            listprojall.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(OnlistItemClick);
        }
    }

    void OnlistItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        var listprojall = sender as ListView;
        var t = tableItems[e.Position];
        Globals.GlobalAskId = t.SubHeading1;
        StartActivity(typeof(Teansrproj));
    }

    // adpater manage
    public class HomeScreenAdapter : BaseAdapter<TableItem>
    {
        List<TableItem> items;
        Activity context;
        public HomeScreenAdapter(Activity context, List<TableItem> items)
            : base()
        {
            this.context = context;
            this.items = items;
        }
        public override long GetItemId(int position)
        {
            return position;
        }
        public override TableItem this[int position]
        {
            get { return items[position]; }
        }
        public override int Count
        {
            get { return items.Count; }
        }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var item = items[position];
            View view = convertView;
            if (view == null) // no view to re-use, create new
                view = context.LayoutInflater.Inflate(Resource.Layout.Ticket_News, null);
            view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Heading;
            view.FindViewById<TextView>(Resource.Id.Text2).Text = item.SubHeading;
            view.FindViewById<TextView>(Resource.Id.Text3).Text = item.SubHeading1;

            return view;
        }
    }

    public class TableItem
    {
        public string Heading;
        public string SubHeading;
        public string SubHeading1;

        public TableItem(string Heading, string SubHeading, string SubHeading1)
        {
            this.Heading = Heading;
            this.SubHeading = SubHeading;
            this.SubHeading1 = SubHeading1;
        }
    }
}

假设您与SELECT u.userid,u.name,u.country GROUP_CONCAT(hobby SEPARATOR ',') FROM hobbies as h join users as u on h.userid=u.userid where h.userid = ? GROUP BY u.userid,u.name,u.country; hobbies有关系。查询将连接连接表的users列,每行将有一个唯一用户。

答案 3 :(得分:0)

这很可能是最快的解决方案

SELECT name, country, telNo, GROUP_CONCAT(hobby)
FROM users u LEFT JOIN hobbies h ON u.id = h.userId
GROUP BY name, country, telNo

有关格式化选项,请参阅https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

它只对最终输出有用,例如,如果您的爱好包含逗号,则您无法唯一地解析它们。